<?php

namespace App\Http\Controllers\Api;

use App\Models\Config;
use App\Models\UserScore;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Score;
use App\Models\Year;
use App\Http\Requests\UserRequest;
use App\Models\User;

class ScoreController extends Controller
{
    public function year_list(Request $request)
    {
        $map = [];
        $request->value && $map['value'] = $request->year;

        $years = Year::where($map);
        $years->whereHas('score', function ($q) {$q->whereNotNull('id');});
        return $years->orderBy('id')->paginate(10);
    }

    public function year_scores(Request $request)
    {
        $map['year_id'] = $request->id;

        $score =  Score::with('user')->where($map);
        $request->name && $score->whereHas('user', function ($q) {$q->where('name', 'like' , '%' .  request('name') . '%');});

        return $score->orderBy('id')->paginate(10);
    }

    public function score_user_list()
    {
       return User::whereHas('roles', function ($q) {$q->whereNotIn('name', ['admin','director','deputy_director']);})->orderBy('id')->get();
    }

    public function store(UserRequest $request)
    {
        $data = [];

        foreach ($request->ids as  $k => $v)
        {
            $data[$k]['user_id'] = \Auth::id();
            $data[$k]['to_user_id'] = $v;
            $data[$k]['year_id'] = $request->id;
            $data[$k]['value'] = $request->values[$k];
        }

        return response()->json(UserScore::insert($data));
    }

    public function user_scores(Request $request)
    {
        $map['user_id'] = \Auth::id();

        $score =  Score::with('year')->where($map);
        $request->year && $score->whereHas('year', function ($q) {$q->where('value', 'like' , '%' .  request('year') . '%');});

        return $score->orderBy('id')->paginate(10);
    }

    //年度评分
    public function year_score_list(Request $request)
    {
        $map = [];
        $request->value && $map['value'] = $request->year;

        $years = Year::where($map)->orderBy('value', 'desc')->paginate(10);

        foreach ($years as $k => $v)
        {
            $user_score = $v->user_score()->where('user_id',\Auth::id())->get();
            $temp = json_decode(json_encode($user_score) , true);

                if(empty($temp))
                {
                   if ($v['value'] == date('Y')) {
                       $v['status'] = 1;
                   } else {
                       $v['status'] = 0;
                   }

                }else{
                    (strtotime($v["value"].'-12-14 18:00:00') > time()) ? $v['status'] = 0:$v['status'] = -1;
                   // $v['status'] = -1;
                }
        }

        return $years;
    }

    //我评过分的列表
    public function year_user_score(Request $request)
    {
        $map['year_id'] = $request->id;
        $map['user_id'] = \Auth::id();

        $score = UserScore::with('to_user')->where($map);
        $request->name && $score->whereHas('to_user', function ($q) {$q->where('name', 'like' , '%' .  request('name') . '%');});

        return $score->orderBy('id')->paginate(10);
    }

    //年度所有用户评分列表
    public function year_user_score_all(Request $request)
    {
        $map['year_id'] = $request->id;

        $score = UserScore::with('user','to_user')->where($map);

        if($request->name) {
            $score->whereHas('user', function ($q) {
                $q->where('name', 'like' , '%' .  request('name') . '%');
            });
        }

        $scores = $score->orderBy('id')->paginate(10);

        return $scores;
    }


    public function createScore(){
        $year =  Year::where('value',date('Y'))->first();
        if($year && isset($year->user_score[0]) && (!isset($year->score))) {
            $users = User::whereHas('roles', function ($q) {
                $q->whereNotIn('name', ['admin', 'director', 'deputy_director']);
            })->get();

            foreach ($users as $user) {
                if ($user->roles[0]->name == 'staff') {
                    $config = Config::where('name', 'staff')->first()->value;

                    $staff_sum = $this->role_score($user,$year->id,['director'],$config[0] / 100);

                    $staff_sum += $this->role_score($user,$year->id,['deputy_director'],$config[1] / 100);

                    $staff_sum += $user->year_score()->where('year_id', $year->id)->whereHas('user.roles', function ($q) {
                            $q->whereIn('name', ['principal', 'main_principal']);
                        })->whereNotIn('user_id',$this->main_principal($user->department_id))
                            ->avg('value') * ($config[2] / 100);

                    $staff_sum += $user->year_score()->where('year_id', $year->id)->whereHas('user.roles', function ($q) {
                            $q->whereIn('name', ['main_principal']);
                        })->whereHas('user', function ($q) use ($user) {
                            $q->where('department_id', $user->department_id);
                        })->avg('value') * ($config[3] / 100);

                    $staff_sum += $this->role_score($user,$year->id,['staff'],$config[4] / 100);
                } else {
                    $config = Config::where('name', 'principal')->first()->value;

                    $staff_sum = $this->role_score($user,$year->id,['director'],$config[0] / 100);

                    $staff_sum += $this->role_score($user,$year->id,['deputy_director'],$config[1] / 100);

                    $staff_sum += $this->role_score($user,$year->id,['principal','main_principal'],$config[2] / 100);

                    $staff_sum += $this->role_score($user,$year->id,['staff'],$config[3] / 100);
                }

                Score::create([
                    'user_id' => $user->id,
                    'year_id' => $year->id,
                    'value' => round($staff_sum, 2),
                ]);
            }

            $director_users = User::whereHas('roles', function ($q) {
                $q->whereIn('name', ['director', 'deputy_director']);
            })->get();

            $year_score_avg = Score::with('user')->where('year_id',$year->id)->whereHas('user.roles', function ($q) {
                $q->whereIn('name', ['principal', 'main_principal']);
            })->avg('value');

            foreach ($director_users as $v) {
                Score::create([
                    'user_id' => $v->id,
                    'year_id' => $year->id,
                    'value' => round($year_score_avg, 2),
                ]);
            }
            return response()->json(['message'=>'评分结算完毕']);
        }else{
            return response()->json(['message'=>'考核未开启'],400);
        }
    }
    private function main_principal($department_id)
    {
        return User::where('department_id', $department_id)->whereHas('roles', function ($q) {
            $q->where('name', 'main_principal');
        })->pluck('id');
    }

    private function role_score($user,$year_id,$role,$config)
    {
        return $user->year_score()->where('year_id', $year_id)->whereHas('user.roles', function ($q) use($role) {
                $q->whereIn('name', $role);
            })->avg('value') * $config;
    }
}
